"""
SimpleAPI ORM 字段类型

提供简化的字段类型接口，完全封装 Tortoise ORM 的字段实现。
用户只需要使用这些字段类型，无需了解底层的 Tortoise 字段。
"""

from typing import Any, Optional, Union, List, Dict, Callable
from decimal import Decimal
import uuid
import datetime

# 导入 Tortoise 字段，但不暴露给用户
from tortoise import fields as tortoise_fields


class BaseField:
    """字段基类"""
    
    def __init__(self, 
                 primary_key: bool = False,
                 unique: bool = False,
                 index: bool = False,
                 null: bool = False,
                 default: Any = None,
                 description: str = None,
                 **kwargs):
        """
        初始化字段
        
        Args:
            primary_key: 是否为主键
            unique: 是否唯一
            index: 是否创建索引
            null: 是否允许为空
            default: 默认值
            description: 字段描述
        """
        self.primary_key = primary_key
        self.unique = unique
        self.index = index
        self.null = null
        self.default = default
        self.description = description
        self.kwargs = kwargs
        
    def get_tortoise_field(self):
        """获取对应的 Tortoise 字段实例"""
        raise NotImplementedError("子类必须实现此方法")


class IntField(BaseField):
    """整数字段"""
    
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        
    def get_tortoise_field(self):
        return tortoise_fields.IntField(
            pk=self.primary_key,
            unique=self.unique,
            index=self.index,
            null=self.null,
            default=self.default,
            description=self.description,
            **self.kwargs
        )


class CharField(BaseField):
    """字符串字段"""
    
    def __init__(self, max_length: int = 255, **kwargs):
        """
        Args:
            max_length: 最大长度
        """
        super().__init__(**kwargs)
        self.max_length = max_length
        
    def get_tortoise_field(self):
        return tortoise_fields.CharField(
            max_length=self.max_length,
            pk=self.primary_key,
            unique=self.unique,
            index=self.index,
            null=self.null,
            default=self.default,
            description=self.description,
            **self.kwargs
        )


class TextField(BaseField):
    """文本字段（长文本）"""
    
    def get_tortoise_field(self):
        return tortoise_fields.TextField(
            pk=self.primary_key,
            unique=self.unique,
            index=self.index,
            null=self.null,
            default=self.default,
            description=self.description,
            **self.kwargs
        )


class BooleanField(BaseField):
    """布尔字段"""
    
    def get_tortoise_field(self):
        return tortoise_fields.BooleanField(
            pk=self.primary_key,
            unique=self.unique,
            index=self.index,
            null=self.null,
            default=self.default,
            description=self.description,
            **self.kwargs
        )


class FloatField(BaseField):
    """浮点数字段"""
    
    def get_tortoise_field(self):
        return tortoise_fields.FloatField(
            pk=self.primary_key,
            unique=self.unique,
            index=self.index,
            null=self.null,
            default=self.default,
            description=self.description,
            **self.kwargs
        )


class DecimalField(BaseField):
    """精确小数字段"""
    
    def __init__(self, max_digits: int = 10, decimal_places: int = 2, **kwargs):
        """
        Args:
            max_digits: 最大位数
            decimal_places: 小数位数
        """
        super().__init__(**kwargs)
        self.max_digits = max_digits
        self.decimal_places = decimal_places
        
    def get_tortoise_field(self):
        return tortoise_fields.DecimalField(
            max_digits=self.max_digits,
            decimal_places=self.decimal_places,
            pk=self.primary_key,
            unique=self.unique,
            index=self.index,
            null=self.null,
            default=self.default,
            description=self.description,
            **self.kwargs
        )


class DateField(BaseField):
    """日期字段"""
    
    def __init__(self, auto_now: bool = False, auto_now_add: bool = False, **kwargs):
        """
        Args:
            auto_now: 每次保存时自动更新
            auto_now_add: 创建时自动设置
        """
        super().__init__(**kwargs)
        self.auto_now = auto_now
        self.auto_now_add = auto_now_add
        
    def get_tortoise_field(self):
        return tortoise_fields.DateField(
            auto_now=self.auto_now,
            auto_now_add=self.auto_now_add,
            pk=self.primary_key,
            unique=self.unique,
            index=self.index,
            null=self.null,
            default=self.default,
            description=self.description,
            **self.kwargs
        )


class DateTimeField(BaseField):
    """日期时间字段"""
    
    def __init__(self, auto_now: bool = False, auto_now_add: bool = False, **kwargs):
        """
        Args:
            auto_now: 每次保存时自动更新
            auto_now_add: 创建时自动设置
        """
        super().__init__(**kwargs)
        self.auto_now = auto_now
        self.auto_now_add = auto_now_add
        
    def get_tortoise_field(self):
        return tortoise_fields.DatetimeField(
            auto_now=self.auto_now,
            auto_now_add=self.auto_now_add,
            pk=self.primary_key,
            unique=self.unique,
            index=self.index,
            null=self.null,
            default=self.default,
            description=self.description,
            **self.kwargs
        )


class TimeField(BaseField):
    """时间字段"""
    
    def __init__(self, auto_now: bool = False, auto_now_add: bool = False, **kwargs):
        """
        Args:
            auto_now: 每次保存时自动更新
            auto_now_add: 创建时自动设置
        """
        super().__init__(**kwargs)
        self.auto_now = auto_now
        self.auto_now_add = auto_now_add
        
    def get_tortoise_field(self):
        return tortoise_fields.TimeField(
            auto_now=self.auto_now,
            auto_now_add=self.auto_now_add,
            pk=self.primary_key,
            unique=self.unique,
            index=self.index,
            null=self.null,
            default=self.default,
            description=self.description,
            **self.kwargs
        )


class ForeignKeyField(BaseField):
    """外键字段"""
    
    def __init__(self, 
                 to: Union[str, type],
                 related_name: str = None,
                 on_delete: str = "CASCADE",
                 **kwargs):
        """
        Args:
            to: 关联的模型类或模型名称
            related_name: 反向关联名称
            on_delete: 删除时的行为 (CASCADE, RESTRICT, SET_NULL)
        """
        super().__init__(**kwargs)
        self.to = to
        self.related_name = related_name
        self.on_delete = on_delete
        
    def get_tortoise_field(self):
        return tortoise_fields.ForeignKeyField(
            model_name=self.to,
            related_name=self.related_name,
            on_delete=getattr(tortoise_fields, self.on_delete, tortoise_fields.CASCADE),
            pk=self.primary_key,
            unique=self.unique,
            index=self.index,
            null=self.null,
            default=self.default,
            description=self.description,
            **self.kwargs
        )


class OneToOneField(BaseField):
    """一对一字段"""
    
    def __init__(self, 
                 to: Union[str, type],
                 related_name: str = None,
                 on_delete: str = "CASCADE",
                 **kwargs):
        """
        Args:
            to: 关联的模型类或模型名称
            related_name: 反向关联名称
            on_delete: 删除时的行为
        """
        super().__init__(**kwargs)
        self.to = to
        self.related_name = related_name
        self.on_delete = on_delete
        
    def get_tortoise_field(self):
        return tortoise_fields.OneToOneField(
            model_name=self.to,
            related_name=self.related_name,
            on_delete=getattr(tortoise_fields, self.on_delete, tortoise_fields.CASCADE),
            pk=self.primary_key,
            unique=self.unique,
            index=self.index,
            null=self.null,
            default=self.default,
            description=self.description,
            **self.kwargs
        )


class ManyToManyField(BaseField):
    """多对多字段"""
    
    def __init__(self, 
                 to: Union[str, type],
                 related_name: str = None,
                 through: str = None,
                 **kwargs):
        """
        Args:
            to: 关联的模型类或模型名称
            related_name: 反向关联名称
            through: 中间表名称
        """
        super().__init__(**kwargs)
        self.to = to
        self.related_name = related_name
        self.through = through
        
    def get_tortoise_field(self):
        return tortoise_fields.ManyToManyField(
            model_name=self.to,
            related_name=self.related_name,
            through=self.through,
            description=self.description,
            **self.kwargs
        )


class JSONField(BaseField):
    """JSON 字段"""
    
    def get_tortoise_field(self):
        return tortoise_fields.JSONField(
            pk=self.primary_key,
            unique=self.unique,
            index=self.index,
            null=self.null,
            default=self.default,
            description=self.description,
            **self.kwargs
        )


class UUIDField(BaseField):
    """UUID 字段"""
    
    def __init__(self, auto_generate: bool = False, **kwargs):
        """
        Args:
            auto_generate: 是否自动生成 UUID
        """
        super().__init__(**kwargs)
        if auto_generate and self.default is None:
            self.default = uuid.uuid4
            
    def get_tortoise_field(self):
        return tortoise_fields.UUIDField(
            pk=self.primary_key,
            unique=self.unique,
            index=self.index,
            null=self.null,
            default=self.default,
            description=self.description,
            **self.kwargs
        )


class BinaryField(BaseField):
    """二进制字段"""
    
    def get_tortoise_field(self):
        return tortoise_fields.BinaryField(
            pk=self.primary_key,
            unique=self.unique,
            index=self.index,
            null=self.null,
            default=self.default,
            description=self.description,
            **self.kwargs
        )


# 便捷的字段创建函数
def primary_key() -> IntField:
    """创建主键字段"""
    return IntField(primary_key=True)


def auto_uuid() -> UUIDField:
    """创建自动生成的 UUID 字段"""
    return UUIDField(auto_generate=True)


def created_at() -> DateTimeField:
    """创建时间字段"""
    return DateTimeField(auto_now_add=True)


def updated_at() -> DateTimeField:
    """更新时间字段"""
    return DateTimeField(auto_now=True)


def foreign_key(to: Union[str, type], **kwargs) -> ForeignKeyField:
    """创建外键字段"""
    return ForeignKeyField(to=to, **kwargs)


def one_to_one(to: Union[str, type], **kwargs) -> OneToOneField:
    """创建一对一字段"""
    return OneToOneField(to=to, **kwargs)


def many_to_many(to: Union[str, type], **kwargs) -> ManyToManyField:
    """创建多对多字段"""
    return ManyToManyField(to=to, **kwargs) 